package com.chazz.filter;

import com.chazz.entity.User;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/admin/*")
public class AuthorizationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取会话
        HttpSession session = request.getSession();
        //从会话中获取用户
        User user = (User) session.getAttribute("user");
        //判断是否存在（是否登录）
        if (user != null) {
            //已登录，继续向下执行
            filterChain.doFilter(request, response);
        } else {
            //没有登录，跳转到登录页面
            response.sendRedirect("../login.html");
        }
    }

    @Override
    public void destroy() {

    }
}
